IF (NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'NUESTRA_RUBIA_ES_MEJOR'))
	BEGIN
		EXEC('Create Schema [NUESTRA_RUBIA_ES_MEJOR] Authorization [gd];')
	END

--Objetos Extra
IF(OBJECT_ID('[NUESTRA_RUBIA_ES_MEJOR].[vwGetNewNumber]','V') IS NULL)
	BEGIN
		EXEC('
		Create View [NUESTRA_RUBIA_ES_MEJOR].[vwGetNewNumber]
		as
		Select Cast(Cast(newid() AS binary(3)) AS int) as NextID')
	END

IF(OBJECT_ID('[NUESTRA_RUBIA_ES_MEJOR].[GetNewNumber]','FN') IS NULL)
	BEGIN
		EXEC('Create Function [NUESTRA_RUBIA_ES_MEJOR].[GetNewNumber] ( ) RETURNS int 
		AS 
			BEGIN
				Declare @code int
				Select top 1  @code=NextID from vwGetNewNumber
				RETURN (@code) 
			END')
	END
GO
IF(OBJECT_ID('[NUESTRA_RUBIA_ES_MEJOR].[GetNewNumber]','FN') IS NULL)
BEGIN
EXEC('
	CREATE Function NUESTRA_RUBIA_ES_MEJOR.GenerarSerial()
		RETURNS varchar(18)
		As
		Begin
			DECLARE @passwordLength smallint
			SET @passwordLength = 18
			DECLARE @password varchar(18)
			declare @characters varchar(100)
			declare @count int

			set @characters = ''

			 set @count = 48
			 while @count <=57
				 begin
					 set @characters = @characters + Cast(CHAR(@count) as char(1))
					 set @count = @count + 1
				 end

			 set @count = 65
			 while @count <=90
				 begin
					 set @characters = @characters + Cast(CHAR(@count) as char(1))
					 set @count = @count + 1
				 end

			 set @count = 97
			 while @count <=122
				 begin
					 set @characters = @characters + Cast(CHAR(@count) as char(1))
					 set @count = @count + 1
				 end

			set @count = 0
			set @password = ''

			 while @count <= @passwordLength
			 begin
			    
				set @password = @password +
				SUBSTRING(@characters,CAST(ABS(CHECKSUM([NUESTRA_RUBIA_ES_MEJOR].[GetNewNumber]()))*1 as
				int)%LEN(@characters)+1,1)
					 set @count = @count + 1
			 end
			RETURN @password
		end
	')
END
